package com.aphrodite.io;

import java.io.IOException;
import java.io.Writer;

/**
 * A character stream that collects its output in a string buffer, which can
 * then be used to construct a string.
 * <p>
 * Closing a StringWriter has no effect. The methods in this class can be called
 * after the stream has been closed without generating an IOException.
 * </p>
 * 
 * @author kentelt
 * 
 */
public class StringWriter extends Writer {
	private StringBuffer buf;

	/**
	 * Create a new string writer, using the default initial string-buffer size.
	 */
	public StringWriter() {
		buf = new StringBuffer();
		lock = buf;
	}

	/**
	 * Create a new string writer, using the specified initial string-buffer
	 * size.
	 * 
	 * @param initialSize
	 *            an int specifying the initial size of the buffer
	 */
	public StringWriter(int initialSize) {
		if (initialSize < 0) {
			throw new IllegalArgumentException("Negative buffer size");
		} else {
			buf = new StringBuffer(initialSize);
			lock = buf;
			return;
		}
	}

	public StringWriter append(char c) {
		write(c);
		return this;
	}

	public void close() throws IOException {

	}

	public void flush() throws IOException {

	}

	public StringBuffer getBuffer() {
		return buf;
	}

	public String toString() {
		return buf.toString();
	}

	/**
	 * Write a portion of an array of characters.
	 * 
	 * @param cbuf
	 *            Array of characters
	 * 
	 * @param offset
	 *            Offset from which to start writing characters
	 * @param len
	 *            Number of characters to write
	 */
	public void write(char cbuf[], int offset, int len) {
		if (offset < 0 || offset > cbuf.length || len < 0 || offset + len > cbuf.length || offset + len < 0)
			throw new IndexOutOfBoundsException();
		if (len == 0) {
			return;
		} else {
			buf.append(cbuf, offset, len);
			return;
		}
	}

	/**
	 * Write a single character.
	 * 
	 * @param c
	 *            int specifying a character to be written.
	 */
	public void write(int c) {
		buf.append((char) c);
	}

	/**
	 * Write a string.
	 * 
	 * @param str
	 *            String to be written
	 */
	public void write(String str) {
		buf.append(str);
	}

	/**
	 * Write a portion of a string.
	 * 
	 * @param str
	 *            String to be written
	 * 
	 * @param offset
	 *            Offset from which to start writing characters
	 * 
	 * @param len
	 *            Number of characters to write
	 */
	public void write(String str, int offset, int len) {
		buf.append(str.substring(offset, offset + len));
	}
}
